import { hapTasks, OhosHapContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { getNode, hvigor } from '@ohos/hvigor'
import { HvigorPlugin,HvigorNode } from '@ohos/hvigor';
import { hapPlugin } from "@hadss/hmrouter-plugin";

const entryNode = getNode(__filename);
// 为此节点添加一个afterNodeEvaluate hook 在hook中修改module.json5的内容并使能
entryNode.afterNodeEvaluate(node => {
  // 获取此节点使用插件的上下文对象 此时为hap插件 获取hap插件上下文对象
  const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
  // 通过上下文对象获取从module.json5文件中读出来的obj对象
  const moduleJsonOpt = hapContext.getModuleJsonOpt();
  // 修改obj对象为想要的，此处举例修改module中的deviceTypes
  moduleJsonOpt['module']['deviceTypes'] = ["phone", "tablet", "2in1", "car"];
  // 将obj对象设置回上下文对象以使能到构建的过程与结果中
  hapContext.setModuleJsonOpt(moduleJsonOpt);
})

function HelloEntry(): HvigorPlugin {
  return {
    pluginId: 'HelloEntry',
    async apply(currentNode: HvigorNode) {

      const hapContext = currentNode.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
      hapContext?.targets((target: Target) =>{
        const targetName = target.getTargetName();
        currentNode.registerTask({
          // 编写自定义任务
          name: `${targetName}@HelloEntry`,
          run: (taskContext) => {
            console.log(`${targetName} ---> Hello HelloEntry!`);
          },
          // 配置前置任务依赖
          dependencies: [`${targetName}@PackageHap`],
          // 配置任务的后置任务依赖
          postDependencies: ['assembleHap']
        })
      })
    }
  }
}


export default {
  system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [HelloEntry(),hapPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}